package com.sgb.kjwl.view.ui.activity.self.websiteManage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtWebsiteBulletinUploadBinding;
import com.sgb.kjwl.model.entity.website.UploadWebsiteBulletinEntity;
import com.sgb.kjwl.utils.ReplaceUtils;
import com.sgb.kjwl.view.widget.manage.MImgGetter;
import com.sgb.kjwl.viewmodel.manage.WebsiteBulletinUploadModel;
import com.sgb.member.MemberConfig;
import com.sgb.member.util.ChooseFileUtil;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.UploadFileBean;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.List;

/**
 * 网站公告上传界面
 * Create by LiWei 2021/11/30
 */
public class WebsiteBulletinUploadActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private AtWebsiteBulletinUploadBinding binding;
    private WebsiteBulletinUploadModel viewModel;
    public static final int RESULT_CODE_SELECT = 100; // 返回
    public static final int REQUEST_CODE_SELECT = 101;// 请求
    //上传公告信息类
    private UploadWebsiteBulletinEntity bulletinEntity;
    private UploadFileBean mUploadFileBean;
    private String body="";
    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, WebsiteBulletinUploadActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_website_bulletin_upload);
        viewModel = new ViewModelProvider(this).get(WebsiteBulletinUploadModel.class);
        binding.include.ivBack.setOnClickListener(this);
        binding.itvBulletinType.setOnWholeItemClickListener(this);
        binding.tvUploadFile.setOnClickListener(this);
        binding.tvFileDelete.setOnClickListener(this);
        binding.tvUploadBulletin.setOnClickListener(this);
        binding.etBulletinContent.setOnClickListener(this);
        binding.include.titleView.setText("公告内容");


        bulletinEntity = new UploadWebsiteBulletinEntity();
        bulletinEntity.setCreateUserName(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, ""));
    }

    @Override
    protected void init() {
        //公告类型列表数据回调
        viewModel.bulletinTypeList.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> bulletinTypeList) {
                showBulletinTypePopWindow(bulletinTypeList);
            }
        });
        //文件上传回调链接
        viewModel.mFileData.observe(this, new Observer<UploadFileBean>() {
            @Override
            public void onChanged(UploadFileBean uploadFileBean) {
                bulletinEntity.setAnnexName(uploadFileBean.getFileName());
                bulletinEntity.setAnnex(uploadFileBean.getUrlPath());
                viewModel.uploadWebsiteBulletin(bulletinEntity);
            }
        });
        //上传公告结果回调
        viewModel.resultUploadBulletin.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String result) {
                if ("ok".equals(result)) {
                    Intent intent = new Intent();
                    intent.putExtra("result", "ok");
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_upload_file:
                //打开文件管理
                ChooseFileUtil.startFileIntent(this);
                break;
            case R.id.tv_file_delete:
                binding.tvUploadFile.setVisibility(View.VISIBLE);
                binding.layoutFile.setVisibility(View.GONE);
                mUploadFileBean = null;
                break;
            case R.id.tv_upload_bulletin:
                uploadFileAndBulletinContent();
                break;
            case R.id.et_bulletin_content:
                viewModel.getH5Url(getActivity(),  body, "quillEditor", REQUEST_CODE_SELECT, "公告内容");
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_bulletin_type:
                viewModel.getBulletinTypeList();
                break;
        }
    }

    private void uploadFileAndBulletinContent() {
        if (bulletinEntity.getType() == -1) {
            MToast.showToast(this, "请选择公告类型");
            return;
        }
        if (TextUtils.isEmpty(binding.etBulletinTitle.getEditContent()) || binding.etBulletinTitle.getEditContent().length() < 5) {
            MToast.showToast(this, "请输入5字以上公告标题");
            return;
        }
        if (TextUtils.isEmpty(body)){
            MToast.showToast(this, "请输入公告内容");
            return;
        }
        bulletinEntity.setTitle(binding.etBulletinTitle.getEditContent());
        bulletinEntity.setContext(body);

        if (mUploadFileBean != null) {
            DialogHelper.showProgressDialog(this, "文件上传中...");
            viewModel.uploadSingleFile(mUploadFileBean);
        } else {
            viewModel.uploadWebsiteBulletin(bulletinEntity);
        }
    }

    /**
     * 展示公告类型列表弹框
     */
    private void showBulletinTypePopWindow(List<String> bulletinTypeList) {
        if (null == bulletinTypeList || bulletinTypeList.size() == 0) {
            MToast.showToast(this, "公告类型列表数据不能为空");
            return;
        }
        OptionsPickerView bulletinTypeOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            binding.itvBulletinType.setContent(bulletinTypeList.get(options1));
            bulletinEntity.setType(options1 + 1);

        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setTitleText("请选择公告类型")
                .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main))
                .build();
        bulletinTypeOption.setPicker(bulletinTypeList);
        bulletinTypeOption.setSelectOptions(0);
        bulletinTypeOption.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == MemberConfig.REQ_FILE_CHOOSE) {//选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                    return;
                }
                ChooseFileUtil.handleFileChoose(getActivity(), data, new SimpleResult<UploadFileBean>() {
                    @Override
                    public void onResult(UploadFileBean uploadFileBean, Object... objects) {
                        mUploadFileBean = uploadFileBean;

                        LogUtil.e("文件获取路径", "文件路径" + uploadFileBean.getFilePath());
                        showUploadFileImgAndName(uploadFileBean);
                    }
                }, 10);
            }
        }
        if (requestCode == REQUEST_CODE_SELECT && resultCode == RESULT_CODE_SELECT) { //企业简介返回
            if (data != null) {
                String body1 = data.getStringExtra("body").trim();
                body =data.getStringExtra("body").trim();
                body1 = ReplaceUtils.INSTANCE.getHtml(body1);
                binding.etBulletinContent.setText(Html.fromHtml(body1, new MImgGetter(getActivity(), binding.etBulletinContent), null));
            }
        }
    }

    /**
     * 展示要上传的的文件名称及文件统一图标
     *
     * @param uploadFileBean 文件管理器获得文件信息
     */
    private void showUploadFileImgAndName(UploadFileBean uploadFileBean) {
        binding.tvUploadFile.setVisibility(View.GONE);
        binding.layoutFile.setVisibility(View.VISIBLE);
        binding.tvFileName.setText(uploadFileBean.getFileName());
        String suffix = uploadFileBean.getExtension();
        if (suffix.equals("pdf")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_pdf));
        }
        if (suffix.equals("txt")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_txt));
        }
        if (suffix.equals("jpg") || suffix.equals("png")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_jpg));
        }
        if (suffix.equals("zip") || suffix.equals("rar")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_zip));
        }
        if (suffix.equals("doc") || suffix.equals("docx")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_doc));
        }
        if (suffix.equals("xls") || suffix.equals("xlsx")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_xls));
        }
        if (suffix.equals("ppt") || suffix.equals("pptx")) {
            binding.ivFileIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_file_ppt));
        }
    }
}
